# -*- coding: utf-8 -*-
import hashlib
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.hashers import make_password
from requests import request
from .models import User, UserNotification
from core.serializers import CustomModelSerializer
from core.validator import CustomValidationError, CustomUniqueValidator
from core.relations import BaseNameWritableRelatedField
from rest_framework import serializers, status


class UserSerializer(CustomModelSerializer):
    """
    用户管理-序列化器
    """

    dept = BaseNameWritableRelatedField()
    roles = BaseNameWritableRelatedField(many=True)

    class Meta:
        model = User
        read_only_fields = ["id"]
        exclude = ["password"]
        extra_kwargs = {
            "post": {"required": False},
        }


class UserCreateSerializer(CustomModelSerializer):
    """
    用户新增-序列化器
    """

    username = serializers.CharField(
        max_length=50,
        validators=[
            CustomUniqueValidator(queryset=User.objects.all(), message="账号必须唯一")
        ],
    )
    password = serializers.CharField(required=False, default=make_password("111111"))

    def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(validated_data["password"])
        user.save()
        return user

    class Meta:
        model = User
        fields = "__all__"
        read_only_fields = ["id"]
        extra_kwargs = {
            "post": {"required": False},
        }


class UserUpdateSerializer(CustomModelSerializer):
    """
    用户修改-序列化器
    """

    username = serializers.CharField(
        max_length=50,
        validators=[
            CustomUniqueValidator(queryset=User.objects.all(), message="账号必须唯一")
        ],
    )
    password = serializers.CharField(required=False, allow_blank=True)

    dept = BaseNameWritableRelatedField()
    roles = BaseNameWritableRelatedField(many=True)

    def save(self, **kwargs):
        data = super().save(**kwargs)
        data.post.set(self.initial_data.get("post", []))
        return data

    class Meta:
        model = User
        read_only_fields = ["id"]
        fields = "__all__"
        extra_kwargs = {
            "post": {"required": False, "read_only": True},
        }


class UserNotificationSerializer(CustomModelSerializer):
    """
    用户通知-序列化器
    """

    class Meta:
        model = UserNotification
        read_only_fields = ["id"]
        fields = "__all__"


class UnreadCountSerializer(serializers.Serializer):
    unread_count = serializers.IntegerField()
